from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.db.models import Sum, Count
from story.models import Story
from interactive.models import Like, Comment

User = get_user_model()

def welcome(request):
    """
    Welcome page view for non-authenticated users.
    """
    if request.user.is_authenticated:
        return redirect('home:home')
    return render(request, 'welcome.html')

@login_required
def home(request):
    """
    Main home page view. Requires login.
    """
    # 获取统计数据
    user_count = User.objects.count()
    story_count = Story.objects.count()
    view_count = Story.objects.aggregate(total_views=Sum('views'))['total_views'] or 0
    ai_story_count = Story.objects.filter(is_draft=False).count()  # 暂时用非草稿故事代替AI生成故事
    like_count = Like.objects.count()
    comment_count = Comment.objects.count()
    
    # 获取所有分类（从Story模型的CATEGORY_CHOICES中获取）
    categories = [{'id': choice[0], 'name': choice[1]} for choice in Story.CATEGORY_CHOICES]
    
    # 获取最近活跃用户 (有发布故事的用户)
    active_users = User.objects.annotate(
        story_count=Count('stories')
    ).filter(story_count__gt=0).order_by('-story_count')[:5]
    
    context = {
        'user_count': user_count,
        'story_count': story_count,
        'view_count': view_count,
        'ai_story_count': ai_story_count,
        'like_count': like_count,
        'comment_count': comment_count,
        'categories': categories,
        'active_users': active_users,
    }
    
    return render(request, 'home.html', context) 